package db

import (
	"github.com/go-redis/redis"
	"gitlab.w2gou.cn/golib/redisex"
	"gitlab.w2gou.cn/xbc/go-lib/log"
	"gitlab.w2gou.cn/xbc/go-lib/util"
)

var rdsObj *redisex.RedisEx

func Init() {
	rdsObj = redisex.NewClient(&redis.Options{
		Addr:         "r-bp1o6uipyth8ndrg6z.redis.rds.aliyuncs.com:6379",
		Password:     "6YwlZi5Ea2beJ5ff",
		DB:           0,
		MinIdleConns: 30,
		PoolSize:     10,
	})
	log.Info4("redis", "redis init", "name", rdsObj.Get("name"))
}

type KeyInfo struct {
	Key    string `json:"key"`
	Remark string `json:"remark"`
	Type   string `json:"typ"`
}

func DocList() []KeyInfo {
	keys := rdsObj.SMembers("doc:list")

	keys = util.SortString(keys)

	pipe := rdsObj.Pipeline()
	for _, key := range keys {
		pipe.Type(key)
		// TODO: 还可以读取 remark
	}

	ks := make([]KeyInfo, 0)

	cs, _ := pipe.Exec()
	for i, c := range cs {
		info := KeyInfo{}
		info.Key = keys[i]

		t := c.(*redis.StatusCmd)

		if t != nil {
			info.Remark = t.Val()
		} else {
			log.Info4("redis_e", "type is nil", "key", keys[i])
		}

		ks = append(ks, info)
	}

	return ks
}

type KeyValue struct {
	Type      string            `json:"typ"`
	StrValue  string            `json:"str_value"`
	ArrValue  []string          `json:"set_value"`
	HashValue map[string]string `json:"hash_value"`
}

func GetValue(key string) KeyValue {
	r := KeyValue{}
	t := rdsObj.Type(key)
	switch t {
	case "string":
		r.StrValue = rdsObj.Get(key)
	case "set":
		r.ArrValue = rdsObj.SMembers(key)
	case "hash":
		r.HashValue = rdsObj.HGetAll(key)
	case "list":
		r.ArrValue = rdsObj.LRange(key, 0, -1)
	}

	return r
}
